package com.sojson.serversocket.config.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sojson.serversocket.config.handler.business.ServerSocketHandlerControl;
import com.sojson.serversocket.config.handler.business.ServerSocketHandlerGetData;
import com.sojson.serversocket.util.ServerSocketUtil;
import com.sojson.serversocket.util.enums.EServerSocketControl;
import com.sojson.util.HexUtil;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * ServerSocket业务包处理器
 *
 * @author liu
 * @date 2024-05-30
 */
@Slf4j
@Component
public class ServerSocketHandlerBusiness {

    @Autowired
    private ServerSocketHandlerGetData getData;
    @Autowired
    private ServerSocketHandlerControl control;

    public void run(ChannelHandlerContext ctx, String addr, String addrRever, String data) {
        // 帧长度
        int len = data.length() / 2;
        // 数据长度域
        String daLen = data.substring(18, 20);
        // 数据域
        String da = data.substring(20, (len - 2) * 2);
        // 校验码
        String verifyCode = data.substring((len - 2) * 2, (len - 1) * 2);

        Byte[] barr = null;

        HexUtil.dataLenVerify(da, daLen, 1);
        HexUtil.dataVerify(data, verifyCode, ServerSocketUtil.HEAD_BUSINESS, (len - 2) * 2);
        String controlCode = data.substring(8 * 2, 9 * 2);

        if (EServerSocketControl.GET_DATA_RESULT_SUCCESS.getCode().equals(controlCode)
            || EServerSocketControl.GET_DATA_RESULT_FAIL.getCode().equals(controlCode)) {
            // 获取电表数据
            if (EServerSocketControl.GET_DATA_RESULT_SUCCESS.getCode().equals(controlCode)) {
                getData.run(ctx, barr, addrRever, data);
            } else {
                getData.error(ctx, addrRever, data);
            }
        } else if (EServerSocketControl.CONTROL_VALUE_RESULT_SUCCESS.getCode().equals(controlCode)
            || EServerSocketControl.CONTROL_VALUE_RESULT_FAIL.getCode().equals(controlCode)) {
            // 跳合闸、报警、保电
            log.info(new StringBuilder("ServerSocket收到控阀包: ").append(addrRever).append(",").append(data).toString());
            if (EServerSocketControl.CONTROL_VALUE_RESULT_SUCCESS.getCode().equals(controlCode)) {
                control.run(ctx, barr, addrRever, data);
            } else {
            }
        } else {
            log.info("此功能未实现");
        }
    }

}